from invoke import task,run
from constants import Report
from constants import Logs
from time import sleep


"""
    1. 外界必须传递进来所要执行的文件名 ，第二个就是
"""

container_name = "$(docker ps -a --format '{{.Names}}' | grep auto_test)"

@task
def init_install(c):
    command = "chmod +x install.sh && dos2unix install.sh && /usr/bin/sh install.sh"
    c.run(command)


@task
def remove_container(c):
    command_down = "docker-compose rm -f -v"
    result = run("docker ps -a --format {{.Names}}",hide=True)
    if result.ok:
        containers = result.stdout.strip().split("\n")
        filtered_containers = [container for container in containers if 'auto_test' in container]
        for container in filtered_containers:
            command_rm = "docker rm {}".format(container)
            c.run(command_rm)

    c.run(command_down)


@task(pre=[init_install,remove_container],post=[remove_container])
def run_cases(c,case_path='test_api',markers='all',browser=''):
    command_report = """docker cp {container_name}:/auto_test/reports/{report_name} reports/""". \
        format(container_name=container_name, report_name=Report.REPORT_FILE)
    command_log = """docker cp {container_name}:/auto_test/logs/{log_name} logs/""". \
        format(container_name=container_name, log_name=Logs.LOG_FILE)
    command_png = """docker cp {container_name}:/auto_test/screen .""". \
        format(container_name=container_name)

    command = """docker-compose run auto_test python3 runner.py -p {case_path} -m {markers}"""

    if 'test_web' in case_path:
        if browser is None or browser == "":
            bro_command = "docker-compose -f docker-compose-web.yml up -d chrome selenium-hub"
        else:
            bro_command = "docker-compose -f docker-compose-web.yml up -d chrome selenium-hub firefox"

        c.run(bro_command)  # 启动浏览器
        sleep(5)
        c.run("echo 启动浏览器")

        c.run(command.format(case_path=case_path, markers=markers))     # 运行自动化测试
        c.run("echo 运行自动化用例完成")

        c.run("echo 拷贝截图，命令为:{}".format(command_png))
        c.run(command_png)      # 拷贝截图
    else:
        c.run(command.format(case_path=case_path, markers=markers))     # 运行自动化测试
        c.run("echo 运行自动化用例完成")

    # 拷贝日志和报告
    c.run("echo 拷贝运行日志,命令为:{}".format(command_log))
    c.run(command_log)

    c.run("echo 拷贝测试报告,命令为:{}".format(command_report))
    c.run(command_report)

